<!--
Copyright (c) 2014 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
Code distributed by Google as part of the polymer project is also
subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
-->

<!--
The `speech-mic` element has a mic icon and tapping on the mic will start the 
speech recognition and invite the user to allow a page access to their
microphone.  Once the access is allowed the user can start talking to the
microphone and transcript will be recorded until the mic is tapped again to
stop the speech recognition.

Example:

    <input value="{{transcript}}">
    <speech-mic transcript="{{transcript}}"></speech-mic>

@element speech-mic
@homepage github.io
-->

<link rel="import" href="../polymer/polymer.html">

<polymer-element name="speech-mic" attributes="language transcript completeTranscript">
<template>

  <link rel="stylesheet" href="speech-mic.css">

  <div id="micContainer" class="mic-container {{ {recognizing: recognizing} | tokenList }}">
    <div class="ring"></div>
    <div class="ring2"></div>
    <div class="icon">
      <svg viewBox="0 0 24 24" height="100%" width="100%" preserveAspectRatio="xMidYMid meet">
        <g><path d="M12,14c1.7,0,3-1.3,3-3l0-6c0-1.7-1.3-3-3-3c-1.7,0-3,1.3-3,3v6C9,12.7,10.3,14,12,14z M17.3,11c0,3-2.5,5.1-5.3,5.1c-2.8,0-5.3-2.1-5.3-5.1H5c0,3.4,2.7,6.2,6,6.7V21h2v-3.3c3.3-0.5,6-3.3,6-6.7H17.3z"></path></g>
      </svg>
    </div>
  </div>
  
</template>
<script>

  (function() {
    
    var SUPPORTED_LANGS = ['af-ZA', 'id-ID', 'ms-MY', 'ca-ES', 'cs-CZ', 'de-DE', 'en-US', 'en-AU', 'en-CA', 'en-IN', 'en-NZ', 'en-ZA', 'en-GB', 'es-AR', 'es-BO', 'es-CL', 'es-CO', 'es-CR', 'es-EC', 'es-SV', 'es-ES', 'es-US', 'es-GT', 'es-HN', 'es-MX', 'es-NI', 'es-PA', 'es-PY', 'es-PE', 'es-PR', 'es-DO', 'es-UY', 'es-VE', 'eu-ES', 'fr-FR', 'gl-ES', 'hr_HR', 'zu-ZA', 'is-IS', 'it-IT', 'it-CH', 'hu-HU', 'nl-NL', 'nb-NO', 'pl-PL', 'pt-BR', 'pt-PT', 'ro-RO', 'sk-SK', 'fi-FI', 'sv-SE', 'tr-TR', 'bg-BG', 'ru-RU', 'sr-RS', 'ko-KR', 'zh-cmn-Hans-CN', 'cmn-Hans-CN', 'cmn-Hans-HK', 'cmn-Hant-TW', 'yue-Hant-HK', 'ja-JP', 'la'];
      
    Polymer('speech-mic', {
      
      /**
       * Fired when the speech recognizer returns a result.
       * 
       * @event speech-mic-result
       * @param {Object} detail
       *   @param {Object} detail.results SpeechRecognitionEvent object
       *   @param {Object} detail.transcript The current transcript string
       *   @param {Object} detail.completeTranscript The complete transcript 
       *                   string for the continuous recognition.
       */
      
      /**
       * Returns the current transcript string.
       *
       * @attribute transcript
       * @type string
       * @default ''
       */
      transcript: '',
      
      /**
       * Returns the complete transcript string for the continuous recognition.
       *
       * @attribute completeTranscript
       * @type string
       * @default ''
       */
      completeTranscript: '',
      
      /**
       * Specifies the language of the speech synthesis for the utterance.
       *
       * @attribute language
       * @type string
       * @default 'en-US'
       */
      language: 'en-US',
      
      eventDelegates: {
        tap: 'toggleRecognition'
      },
      
      ready: function() {
        if (window.webkitSpeechRecognition) {
          this.recognition = new webkitSpeechRecognition();
          this.recognition.continuous = true;
          this.recognition.interimResults = true;
          this.recognition.lang = this.language;
          this.recognition.onstart = this.start.bind(this);
          this.recognition.onend = this.end.bind(this);
          this.recognition.onresult = this.result.bind(this);
          this.recognition.onerror = this.error.bind(this);
        } else {
          this.style.display = 'none';
        }
      },
      
      languageChanged: function() {
        if (!this.recognition) {
          return;
        }
        this.recognition.lang = this.findSupportedLang(this.language);
      },
      
      findSupportedLang: function(l) {
        if (SUPPORTED_LANGS.indexOf(l) >= 0) {
          return l;
        } else {
          var ll = l.substring(0, 2);
          for (var i = 0, sl; sl = SUPPORTED_LANGS[i]; i++) {
            if (sl.indexOf(ll) == 0) {
              return sl;
            }
          }
        }
      },
      
      toggleRecognition: function() {
        if (!this.recognition) {
          return;
        }
        if (this.recognizing) {
          this.recognition.stop();
        } else {
          this.recognition.start();
        }
      },
      
      start: function(e) {
        this.recognizing = true;
      },
      
      end: function() {
        this.recognizing = false;
      },
      
      stop: function() {
        this.recognition && this.recognition.stop();
      },
      
      result: function(e) {
        var t, ct = '', isFinal;
        for (var i = 0, r; r = e.results[i]; i++) {
          t = r[0] && r[0].transcript || '';
          ct += t;
          isFinal = r.isFinal;
        }
        this.transcript = t;
        this.completeTranscript = ct;
        this.fire('speech-mic-result', {
          results: e.results,
          transcript: t,
          completeTranscript: ct,
          isFinal: isFinal
        });
      },
      
      error: function(e) {
        console.log(e);
      }
      
    });
  
  })();
  
</script>
</polymer-element>
